package com.rongke.web;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.rongke.commons.JsonResp;
import com.rongke.model.*;
import com.rongke.redis.CacheUtil;
import com.rongke.service.*;
import com.rongke.utils.StringUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.lang.reflect.Field;
import java.util.*;

/**
 * @version : Ver 1.0
 * @GoodsController
 * @商品Controller
 */
@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping(value = "/api/goods")
@Transactional
public class GoodsController {
    private Logger log = Logger.getLogger(this.getClass());
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private PanicBuyingGoodsService panicBuyingGoodsService;
    @Autowired
    private CacheUtil cacheUtil;
    @Autowired
    private IndexGroupService indexGroupService;
    @Autowired
    private GoodsDetailService goodsDetailService;

    @Autowired
    private ClassifyService classifyService;

    @Autowired
    private  OrdersService ordersService;
    @Autowired
    private SystemParmService systemParmService;

    /**
     * @param goods
     * @return 返回值JsonResp
     * @添加商品
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public JsonResp addGoods(@RequestBody Goods goods) {
        log.debug("添加商品");
        goods.setGmtDatetime(new Date());
        goodsService.insert(goods);
        return JsonResp.ok(goods);
    }


    /**
     * @param goods
     * @return
     * @添加或修改商品
     */
    @RequestMapping(value = "/saveOrUpdate", method = RequestMethod.POST)
    public JsonResp saveOrUpdate(@RequestBody Goods goods) {
        log.debug("添加或修改商品");
        if (goods.getGoodsType() == null)
            return JsonResp.toFail("没有选择商品线！");
        if (goods.getClassifyId() == null)
            return JsonResp.toFail("没有选择具体的商品分类！");
        //添加
        if (goods.getId() == null) {
            goods.setGmtDatetime(new Date());
            goodsService.insert(goods);
        } else {
            //修改
            goods.setUptDatetime(new Date());
            goodsService.updateById(goods);
        }
        return JsonResp.ok(goods);
    }

    /**
     * @param goods
     * @return 返回值JsonResp
     * @修改商品
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public JsonResp updateGoods(@RequestBody Goods goods) {
        log.debug("修改商品");
        goods.setUptDatetime(new Date());
        goodsService.updateById(goods);
        return JsonResp.ok(goods);
    }

    /**
     * 批量更新商品
     * @param goodsList
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/uptGoodsBatch", method = RequestMethod.POST)
    public JsonResp uptGoodsBatch(@RequestBody List<Goods> goodsList) {
        log.debug("批量更新商品");
        if(goodsList.size()==0)
            return JsonResp.toFail("server:添加的商品为空！");
        for(int i=0;i<goodsList.size();i++){
            goodsList.get(i).setUptDatetime(new Date());
        }
        goodsService.updateBatchById(goodsList);
        return JsonResp.ok(goodsList);
    }

    /**
     * 获取购买商品返现手续费比率，小数
     * @return
     */
    @RequestMapping(value = "/getProcedureRate",method = RequestMethod.GET)
    public JsonResp getProcedureRate(){
        log.debug("获取购买商品手续费比率，小数");
        Double procedureRate=0.07;
        List<SystemParm> sysparms=systemParmService.selectList(null);
        SystemParm sysparm=sysparms.get(0);
        if(sysparm.getCashBackPoundage()==null){
            return JsonResp.toFail("未设置返现手续费");

        }
        procedureRate =sysparm.getCashBackPoundage();
        return JsonResp.ok(procedureRate);
    }

    /**
     * @后台将商品移出分组，置index_group_id为null
     * @param idsMap 传入的商品id集合
     * @return
     */
    @RequestMapping(value = "/uptToNullGroup",method = RequestMethod.POST)
    public JsonResp uptToNullGroup(@RequestBody Map<String,Object> idsMap){
        log.debug("后台将商品移出分组，置index_group_id为null");
        String groupId= (String) idsMap.get("groupId");
        List<Integer> ids= (List<Integer>) idsMap.get("ids");
        if(StringUtil.isEmpty(groupId)||null==ids||ids.size()==0)
            return JsonResp.toFail("参数不能为空！");
       goodsService.uptToNullGroup(idsMap);
        return JsonResp.ok(idsMap);
    }

    /**
     * @param id
     * @return
     */
    @RequestMapping(value = "/deleteGoodsOne", method = RequestMethod.GET)
    public JsonResp deleteGoodsOne(Long id) {
        log.debug("删除某个商品,级联删除sku表等信息");
        EntityWrapper<GoodsDetail> ew = new EntityWrapper<>();
        ew.eq("goods_id", id);
        goodsDetailService.delete(ew);
        goodsService.deleteById(id);
        return JsonResp.ok("删除商品成功");
    }

    /**
     * @param id
     * @return 返回值JsonResp
     * @根据id查找商品
     */
    @RequestMapping(value = "/selectOne", method = RequestMethod.GET)
    public JsonResp selectGoods(Long id) {
        log.debug("查找商品");
        Goods goods = goodsService.selectById(id);
        return JsonResp.ok(goods);
    }

    /**
     * @param page
     * @return
     * @搜索和分类进入根据二级分类id获取商品列表
     */
    @RequestMapping(value = "/selectGoodsByClassifyId", method = RequestMethod.GET)
    public JsonResp selectGoodsByClassifyId(String classifyId, Page page) {
        log.debug("根据二级分类id获取商品列表");
        EntityWrapper<Goods> ew = new EntityWrapper<>();
        //先获取查询二级分类的下一级分类集合（仅适用于三级以内）
        Map<String,Object> map=new HashMap<>();
        map.put("classify_type",classifyId);
        List<Classify> classifyList=classifyService.selectByMap(map);
        if(classifyList.size()==0){
            ew.eq("classify_id", classifyId);
        }
        if(classifyList.size()>0){
            List<Long> cids=new ArrayList<>();
            for(Classify c:classifyList){
                cids.add(c.getId());
            }
            ew.in("classify_id",cids);
        }
        ew.orderBy("gmt_datetime",false);
        Page<Goods> goodsPage = goodsService.selectPage(page, ew);
        return JsonResp.ok(goodsPage);
    }

    /**
     * @param token 用户令牌  goodsId 商品id  type 1代表提醒我2代表取消提醒
     * @return 返回值JsonResp
     * @即将开始抢购商品设置（提醒我、取消提醒）
     */
    @RequestMapping(value = "/setRemindMe", method = RequestMethod.GET)
    public JsonResp setRemindMe(String token, Long goodsId, Integer type) {
        log.debug("即将开始抢购商品设置（提醒我、取消提醒）");
        if(!cacheUtil.hasKey(token)){
            return JsonResp.fa("未登录或登录超时，请重新登录");
        }
        Long userId=Long.valueOf(cacheUtil.get(token));
        EntityWrapper<PanicBuyingGoods> ew = new EntityWrapper<>();
        ew.eq("panic_status", "未开始");
        ew.eq("goods_id", goodsId);
        PanicBuyingGoods pbg = panicBuyingGoodsService.selectOne(ew);
        if (pbg == null) {
            return JsonResp.fa("该活动尚未开始");
        }


        if (type == 1) {
            try {
//                cacheUtil.put("aaa",String.valueOf(type));
                cacheUtil.sendString("aaa", 4);
            } catch (Exception e) {
                e.printStackTrace();
            }
//            jedis.set(String.valueOf(userId),String.valueOf(type));
        } else if (type == 2) {
            try {
                cacheUtil.put("aaa", String.valueOf(type));
            } catch (Exception e) {
                e.printStackTrace();
            }
//            jedis.set(String.valueOf(userId),String.valueOf(type));
        }
        //取消消息定时推送
        panicBuyingGoodsService.remindTask(userId, null, type);
        panicBuyingGoodsService.updateById(pbg);
        return JsonResp.ok();
    }


    /**
     * 后台分页获取所有商品列表（默认时间倒序）
     * @param goodsPage
     * @return
     */
    @RequestMapping(value = "/getAllPageableGoods",method = RequestMethod.POST)
    public JsonResp getAllPageableGoods(@RequestBody GoodsPage goodsPage){
        log.debug("后台分页获取所有商品列表（默认时间倒序）");
        Goods goods=goodsPage.getGoods();
        Page page=goodsPage.getPage();
        EntityWrapper<Goods> ew =new EntityWrapper<>();
        //添加时间倒序
        ew.orderBy("gmt_datetime",false);
        //已发布的该产品线下在售的商品（不包括自身和已推荐商品）
        if(null!=goods.getGoodsStatus()){
            ew.eq("goods_status",goods.getGoodsStatus());
        }
        if(null!=goods.getGoodsType()){
            ew.eq("goods_type",goods.getGoodsType());
        }
        if(null!=goods.getClassifyId())
            ew.eq("classify_id",goods.getClassifyId());
        if(null!=goods.getIndexGroupId())
            ew.eq("index_group_id",goods.getIndexGroupId());
        //搜索
        if(null!=goodsPage.getSearchText())
            ew.like("goods_name",goodsPage.getSearchText());
        Page<Goods> gdPage=goodsService.selectPage(page,ew);
        return JsonResp.ok(gdPage);
    }

    public boolean IsNotNullEntity(Object obj) throws IllegalAccessException {
        int modCount=0;
        for (Field f : obj.getClass().getDeclaredFields()) {
            f.setAccessible(true);
            if (f.get(obj) == null) { //判断字段是否为空，并且对象属性中的基本都会转为对象类型来判断
            continue;
            }else{
                modCount+=1;
            }
        }
        if(modCount>0)
            return true;
        else return false;
    }

    /**
     * @param sid 分类id
     * @param type 产品线
     * @param page
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/selectiveGoodsList", method = RequestMethod.GET)
    public JsonResp selectiveGoodsList(Long sid, Integer type, Page page) {
        log.debug("根据分类id查询产品列表");
        EntityWrapper<Goods> ew = new EntityWrapper<>();
        ew.orderBy("gmt_datetime",false);
        if (sid != null) {
            ew.eq("classify_id", sid);
        }
        if (type != null) {
            ew.eq("goods_type", type);
        }
        ew.eq("goods_status",2);
        Page<Goods> goodsPage = goodsService.selectPage(page, ew);
        if(!goodsPage.getRecords().isEmpty()){
            goodsPage.getRecords().forEach(e->{
                goodsService.fetchGoodsInventoryStatus(e);//判断库存状态
            });
        }
        return JsonResp.ok(goodsPage);
    }

    /**
     * 分页获取某产品线下已发布未分组的商品
     * @param goodsPage 包含Goods和Page的包装类
     * @return
     */
    @RequestMapping(value = "/getNotGroupedGoods",method = RequestMethod.POST)
    public JsonResp getNotGroupedGoods(@RequestBody GoodsPage goodsPage ){
        log.debug("分页获取某产品线下未分组的商品集合");
        Goods goods=goodsPage.getGoods();
        if(null==goods.getGoodsType())
            return JsonResp.toFail("参数不能为null");
        Page page=goodsPage.getPage();
        EntityWrapper<Goods> ew=new EntityWrapper<>();
        ew.eq("goods_type",goods.getGoodsType()).isNull("index_group_id").eq("goods_status",2);
        //搜索
        if (null != goodsPage.getSearchText())
            ew.like("goods_name", goodsPage.getSearchText());
        Page<Goods> gdPage=goodsService.selectPage(page,ew);
        return JsonResp.ok(gdPage);
    }

    /**
     * 分页获取某二级分组下的已发布商品列表
     * @param groupId
     * @return
     */
    @RequestMapping(value = "/getPublishedGoodsByIndexGroupId",method = RequestMethod.GET)
    public JsonResp getPublishedGoodsByIndexGroupId(Long groupId,Page page){
        log.debug("分页获取某二级分组下的已发布商品列表");
        if(null==groupId)
            return JsonResp.toFail("参数不能为空");
        EntityWrapper<Goods> ew =new EntityWrapper<>();
        ew.eq("index_group_id",groupId).eq("goods_status",2);
        ew.orderBy("gmt_datetime",false);
        Page<Goods> goodsPage=goodsService.selectPage(page,ew);
        if(!goodsPage.getRecords().isEmpty()){
            goodsPage.getRecords().forEach(e->{
                goodsService.fetchGoodsInventoryStatus(e);//判断库存状态
            });
        }
        return JsonResp.ok(goodsPage);
    }

    /**
     * 后台分组管理分页获取某二级分组下的已发布商品列表
     * @param goodsPage goods和page的封装类
     * @return
     */
    @RequestMapping(value = "/getPubGoodsByIndexGroupId",method = RequestMethod.POST)
    public JsonResp getPubGoodsByIndexGroupId(@RequestBody GoodsPage goodsPage){
        log.debug("后台分组管理分页获取某二级分组下的已发布商品列表");
        Goods goods=goodsPage.getGoods();
        if(null==goods.getIndexGroupId())
            return JsonResp.toFail("参数不能为null");
        Page page=goodsPage.getPage();
        EntityWrapper<Goods> ew=new EntityWrapper<>();
        ew.eq("index_group_id",goods.getIndexGroupId()).eq("goods_status",2);
        ew.orderBy("gmt_datetime",false);
        //搜索
        if (null != goodsPage.getSearchText())
            ew.like("goods_name", goodsPage.getSearchText());
        Page<Goods> gdPage=goodsService.selectPage(page,ew);
        return JsonResp.ok(gdPage);
    }

    /**
     * 获取某产品线下已发布未分组的商品集合（交给web客户端分页）
     * @param goodsType
     * @return
     */
    @RequestMapping(value = "/getNotGroupedGoodsList",method = RequestMethod.GET)
    public JsonResp getNotGroupedGoodsList(int goodsType){
        log.debug("获取某产品线下未分组的商品集合");
        EntityWrapper<Goods> ew=new EntityWrapper<>();
        //goods_status 商品状态 1代表只上传未发布 2代表正式发布上架 3 下架
        ew.eq("goods_status",2).eq("goods_type",goodsType).isNull("index_group_id");
        List<Goods> goodsList=goodsService.selectList(ew);
        return JsonResp.ok(goodsList);
    }


    /**
     * 获取某二级分组下的已发布商品列表（交给web客户端分页）
     * @param groupId
     * @return
     */
    @RequestMapping(value = "/getPublishedGoodsListByIndexGroupId",method = RequestMethod.GET)
    public JsonResp getPublishedGoodsListByIndexGroupId(Long groupId){
        log.debug("获取某二级分组下的已发布商品列表");
        if(null==groupId)
            return JsonResp.toFail("参数不能为空");
        EntityWrapper<Goods> ew =new EntityWrapper<>();
        ew.eq("index_group_id",groupId).eq("goods_status",2);
        List<Goods> goodsList=goodsService.selectList(ew);
        return JsonResp.ok(goodsList);
    }


    /**
     * 分页获取某二级分组下的所有状态商品列表（分组已带产品线）
     * @param groupId
     * @return
     */
    @RequestMapping(value = "/getWholeGoodsByIndexGroupId",method = RequestMethod.GET)
    public JsonResp getWholeGoodsByIndexGroupId(Long groupId,Page page){
        log.debug("分页获取某二级分组下的所有状态商品列表");
        if(null==groupId)
            return JsonResp.toFail("参数不能为空");
        EntityWrapper<Goods> ew =new EntityWrapper<>();
        ew.eq("index_group_id",groupId);
        Page<Goods> goodsPage=goodsService.selectPage(page,ew);
        return JsonResp.ok(goodsPage);
    }

    /**
     * 获取品牌推荐商品列表
     * @param page
     * @return
     */
    @RequestMapping(value = "/getGoodsListByIndexGroupId",method = RequestMethod.GET)
    public JsonResp getGoodsListByIndexGroupId(Page page){
        log.debug("获取品牌推荐商品列表");
        EntityWrapper<IndexGroup> ew=new EntityWrapper<>();
        ew.eq("group_type",2);
        ew.eq("is_homepage",1);
       IndexGroup indexGroup=indexGroupService.selectOne(ew);
        if(indexGroup==null){
            return JsonResp.fa("品牌推荐尚未添加主页显示商品");

        }
        EntityWrapper<Goods> ewGoods =new EntityWrapper<>();
        ewGoods.eq("index_group_id",indexGroup.getId());
        Page<Goods> goodsPage=goodsService.selectPage(page,ewGoods);
        return JsonResp.ok(goodsPage);
    }

    /**
     * 获取用户已购买的商品
     * @param muserId
     * @return
     */
    @RequestMapping(value = "/getBuyGoods",method = RequestMethod.GET)
    public JsonResp getGoodsListByIndexGroupId(Long muserId){
        List<Goods> buyGoods = goodsService.getBuyGoods(muserId);
        return JsonResp.ok(buyGoods);
    }

    /**
     * 商品搜索
     * @param q 关键词
     * @return
     */
    @RequestMapping(value = "/search",method = RequestMethod.GET)
    public JsonResp search(String q,Page page){
        log.debug("商品搜索");
        log.debug("搜索关键词为"+q);
        if(StringUtil.isEmpty(q)){
            return JsonResp.toFail("搜索关键词不能为空");
        }
        EntityWrapper<Goods> ew=new EntityWrapper<>();
        ew.like("goods_name",q);
        ew.eq("goods_status",2);
        page=goodsService.selectPage(page,ew);
        return JsonResp.ok(page);
    }


}
